package com.zrb.discover;

import java.util.List;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.zrb.discover.adapter.FundAdapter;
import com.zrb.discover.bean.UserInfoJson;
import com.zrb.discover.widget.PullToZoomListView;
import com.zrb.mobile.R;
 
 
import com.zrb.mobile.adapter.Discover_listAdapter.onActionlistener;
import com.zrb.mobile.adapter.model.DiscoverDto;
import com.zrb.mobile.adapter.model.DiscoverDtos;
import com.zrb.mobile.ui.CircleImageView;
import com.zrb.mobile.utility.CollectionHelper;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.DialogBuilder;
import com.zrb.mobile.utility.ViewUtil;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.CollectionHelper.onCollectionListener;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class UserDetailActivity extends Activity implements onActionlistener,onCollectionListener{
	private static final String LOG_TAG = "UserDetailActivity";
	private int mUserId = 0;
	private static final int DEFAULT_USER_ID = 0;
	private PullToZoomListView mIntentionListView = null;
	private int mCurrentPage = 0;
	Handler mHandler = new Handler();
	FundAdapter mFundAdapter;
	private CircleImageView mCircleImageView = null;
	private TextView mUserNameView = null;
	private TextView mJobView = null;
	private String mUserName = "";
	private String mAvatarUrl = "";
	private String mOrg = "";
	private String mIndustry = "";
	private String mJob = "";
	Handler mhandler = new Handler();
	private View customNav;
	private View mHeadViewContainer = null;
	private View mTitleAndBack;
	private RelativeLayout mRefreshLayout;
	private View loadingView;
	private Dialog PopDialog;
	private RelativeLayout mBack;
	private ImageView mTitleView;
	private boolean mHeadDescriptionLoaded = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	 	setContentView(R.layout.user_detail_listview);
	 	initData();
	 	initView();
		completeLoad();
		requestData();
	 	regFocusNumBoradcastReceiver();
	}
	
	private void initData(){
		mUserName = getIntent().getStringExtra(UserCardDetailActivity.USER_NAME); 
	 	mUserId = getIntent().getIntExtra(UserCardDetailActivity.USER_ID, DEFAULT_USER_ID);
	 	mAvatarUrl = getIntent().getStringExtra(UserCardDetailActivity.USER_AVATAR_URL);
	 	mOrg = getIntent().getStringExtra(UserCardDetailActivity.USER_ORG);
	 	mJob = getIntent().getStringExtra(UserCardDetailActivity.USER_JOB);	
	 	mIndustry = getIntent().getStringExtra(UserCardDetailActivity.USER_INDUSTRY);
	 	
	}

	private void initView() {
		View mHeadViewContainer = this.getLayoutInflater().inflate(R.layout.dynamic_user_detail, null);
		mTitleAndBack = this.getLayoutInflater().inflate(R.layout.user_detail_head, null);
		mCircleImageView = (CircleImageView) mHeadViewContainer.findViewById(R.id.business_user_avatar);
		mUserNameView = (TextView) mHeadViewContainer.findViewById(R.id.business_user_name);
		mJobView = (TextView) mHeadViewContainer.findViewById(R.id.business_user_job);
		mRefreshLayout = (RelativeLayout) findViewById(R.id.refresh_layout);
		mIntentionListView = (PullToZoomListView) findViewById(android.R.id.list);
		mIntentionListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
		mBack  = (RelativeLayout) findViewById(R.id.back);  
		mIntentionListView.addHeadView(mHeadViewContainer,mTitleAndBack);
	 
	 
		LayoutInflater inflater = LayoutInflater.from(this);
		loadingView = inflater.inflate(R.layout.ss_new_comment_footer, null);
		mIntentionListView.addFooter(loadingView);
		mIntentionListView.setPageSize(10);
		mFundAdapter = new FundAdapter(this);
		mFundAdapter.setOnAction(this);
		mIntentionListView.setAdapter(mFundAdapter);
		mIntentionListView.setOnRefreshListener(mRefreshListener);
		mIntentionListView.setOnLoadListener(mLoadListener);
		mBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
					setforResult();
					UserDetailActivity.this.finish();
			}
		});
		mTitleView = (ImageView) findViewById(R.id.head_title_layout);
		//mTitleView.setAlpha(0.0f);
		mIntentionListView.setHeadScrollInterface(mHeadScrollInterface);
	}

	private void fillData(){
		ViewUtil.showUserAvatar(mCircleImageView,mAvatarUrl);
		if(TextUtils.isEmpty(mUserName)){
			mUserName = getResources().getString(R.string.anonymity);
		}
		mUserNameView.setText(mUserName);
		String str = "";
		if(!TextUtils.isEmpty(mIndustry)){
			str = mIndustry;
		}
		if(!TextUtils.isEmpty(mOrg)){
			if(!TextUtils.isEmpty(mIndustry)){
				str = str + Constants.FLAG;
			}
			str = str + mOrg;
		}
		if(!TextUtils.isEmpty(mJob)){
			if(!TextUtils.isEmpty(mIndustry) || !TextUtils.isEmpty(mOrg)){
				str = str + Constants.FLAG;
			}
			str = str + mJob;
		}
		if(TextUtils.isEmpty(str)){
			str = getResources().getString(R.string.secrecy);
		}
		mJobView.setText(str);       
	}
	
	PullToZoomListView.OnRefreshListener mRefreshListener = 
			new PullToZoomListView.OnRefreshListener() {
		
		@Override
		public void onRefresh() {
			if(mIntentionListView.isLoading()){
				return;
			}
//			Log.d("outputdata","onRefresh mHeadDescriptionLoaded:" + mHeadDescriptionLoaded);
			if(mHeadDescriptionLoaded){
				startRefresh();
				requestIntentionList();
			}else{
				requestData(); 
			}
		}
	};
	
	private void requestData() {
		startRefresh();
		loadUserDescriptionData();
	}
	
	private void requestIntentionList(){
		mCurrentPage = 1;
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				loadUserFundData(-1, true);
			}
		}, 1000);
	}
	
	PullToZoomListView.OnLoadListener mLoadListener = new PullToZoomListView.OnLoadListener() {
		
		@Override
		public void onLoadMore() {
			mCurrentPage++;
			mhandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					if(mIntentionListView.isRefreshing()){
						return;
					}
					loadUserFundData(mFundAdapter.getMinId(), false);
				}
			}, 400);
		}
	};
	
	ZrbRestClient mZrbRestClient;
	
	private void loadUserFundData(long maxId, final boolean isreflesh) {
		if(!isreflesh){
			startLoad();
		}
		RequestParams param = new RequestParams();
		// param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
		param.put("limit", 5);
		param.put("uid", mUserId);
		if (-1 != maxId) {
			param.put("maxId",maxId);
		}
//		CommonUtil.InfoLog("businessCard/queryFundList", param.toString());
		Log.d("outputdata","loadUserFundData param:" + param.toString());
		String url = "intention/listByUser?" + param.toString();
		if(mZrbRestClient==null){
			mZrbRestClient=new ZrbRestClient(this);
		}
		mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				Log.d(LOG_TAG,"onFailure");
				CommonUtil.showToast(arg0, UserDetailActivity.this);
				completeRefresh();
				completeLoad();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String results = new String(arg2);
				Log.d(LOG_TAG,"onSuccess:" + results);
				if (mCurrentPage == 1){
					completeRefresh();
				}
				try {
					Gson gson = new Gson();
					DiscoverDtos fundJson = gson.fromJson(results,
							DiscoverDtos.class);
					if (fundJson.res == 1) {

						if (fundJson.data != null && fundJson.data.size() > 0) {
						/*	if (mCurrentPage == 1) {
								mFundAdapter.setDatas(fundJson.data);
							} else {
								mFundAdapter.addAll(fundJson.data);
								completeLoad();
							}*/
							mFundAdapter.notifyDataSetChanged();
						} else {
							completeLoad();
							CommonUtil.showToast(String.format("暂无%1$s信息~~",
									mCurrentPage == 0 ? "" : "更多"),
									UserDetailActivity.this);
						}

					} else
						CommonUtil.showToast(fundJson.msg, UserDetailActivity.this);
				} catch (Exception e) {
					CommonUtil.showToast(UserDetailActivity.this
							.getString(R.string.error_serverdata_loadfail),
							UserDetailActivity.this);
				}
			}
		});
		mZrbRestClient.sessionGet(url);
	}
	
	private void loadUserDescriptionData() {
		RequestParams param = new RequestParams();
		param.put("userId", mUserId);
		Log.d("outputdata","businessCard/myCard:" + param.toString());
		String url = "businessCard/myCard"/* + param.toString()*/;
		if(mZrbRestClient==null){
			mZrbRestClient=new ZrbRestClient(this);
		}
		mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener(){
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				Log.d(LOG_TAG,"onFailure");
				CommonUtil.showToast(R.string.error_net_loadfail,
						UserDetailActivity.this);
				completeRefresh();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String results = new String(arg2);
				try {
					Gson gson = new Gson();
					UserInfoJson fundJson = gson.fromJson(results,
							UserInfoJson.class);
					if (fundJson.res == 1) {

						if (fundJson.data != null) {
							UserInfoJson.UserInfo userInfo = fundJson.data;
							mUserName = userInfo.realName;//.realName;
							mAvatarUrl = userInfo.avatar;//.avatar;
							mOrg = userInfo.org;//.org;
							mJob = userInfo.position;
							mIndustry = userInfo.industryName;//.industry;
 
						} else {
							CommonUtil.showToast(String.format("暂无%1$s信息~~",
									mCurrentPage == 0 ? "" : "更多"),
									UserDetailActivity.this);
						}
					} else{
						CommonUtil.showToast(fundJson.msg, UserDetailActivity.this);
					}
				} catch (Exception e) {
					CommonUtil.showToast(UserDetailActivity.this
							.getString(R.string.error_serverdata_loadfail),
							UserDetailActivity.this);
				}
			 	fillData();
		        requestIntentionList();
			}
		});
		mZrbRestClient.post(url,param);
	}
	
	public void completeRefresh(){
		mRefreshLayout.setVisibility(View.GONE);
		mIntentionListView.refreshComplete();
	}
	
	public void completeLoad(){
		loadingView.setVisibility(View.INVISIBLE);
		mIntentionListView.loadComplete();
	}
	
	public void startRefresh(){
		mRefreshLayout.setVisibility(View.VISIBLE);
		mIntentionListView.startRefresh();
	}
	
	public void startLoad(){
		loadingView.setVisibility(View.VISIBLE);
	}

	CollectionHelper mCollectionHelper;
	
	@Override
	public void onAttentionEvent(int postion) {
		/*if (null == mCollectionHelper) {
			mCollectionHelper = new CollectionHelper(this,
					Constants.FocusIntent);
			mCollectionHelper.setOnCollectionListener(this);
		}

		DiscoverDto tmpDto = mFundAdapter.mCurrentDatas.get(postion);
		mCollectionHelper.curPostion = postion;
		mCollectionHelper.onClickCollect(tmpDto.id,
				tmpDto.attention == 0 ? true : false);*/
	}

	@Override
	public void showLoginDialog(String msg) {
		DialogBuilder builder2 = new DialogBuilder(this);
		// builder2.setTheme(Resource.Style.customDialog);
		builder2.setTitle("登录提示");

		builder2.setShowAlert(true);
		View view = View.inflate(this,
				R.layout.longin_dialog_view, null);
		TextView textView = (TextView) view.findViewById(R.id.tipss);
		textView.setText(msg);
		builder2.setContentView(view);
		builder2.setPositiveTitle("马上登录");
		builder2.setCloseOnclick(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PopDialog.dismiss();
				if (arg0.getId() == R.id.btn_confirm) {
					com.zrb.mobile.register.User_phone_login.launch(UserDetailActivity.this, false);
				 
				}
			}
		});
		PopDialog = builder2.create();
		PopDialog.show();
	}

	@Override
	public void onCollectionEvent() {
		/*DiscoverDto tmpDto = mFundAdapter.mCurrentDatas.get(mCollectionHelper.curPostion);
		tmpDto.attentionTimes += tmpDto.attention == 0 ? 1 : -1;
		tmpDto.attention = tmpDto.attention == 0 ? 1 : 0;
		mFundAdapter.notifyDataSetChanged();*/
	}
	
	private BroadcastReceiver mFocusNumBroadcastReceiver1 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Constants.FocusNum_Find_mainlist)) {
				String from = intent.getStringExtra("from");
				int position = intent.getIntExtra("position", -1);
				if ("2".equals(from)) {
					addCount(position);
				}
//				if ("1".equals(from)) {
//					int attention = intent.getIntExtra(x"attention", -1);
//					if (attention != -1) {
//						if (attention == 0) {
//							// 取消关注
//							CanFocus(position);
//						} else {
//							// 添加关注
//							AddFocus(position);
//						}
//					}
//
//				}
			}
		}
	};

	protected void addCount(int position) {
		/*mFundAdapter.mCurrentDatas.get(position).messageAmount = mFundAdapter.mCurrentDatas
				.get(position).messageAmount + 1;
		mFundAdapter.notifyDataSetChanged();*/
	}
	
	public void regFocusNumBoradcastReceiver() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(Constants.FocusNum_Find_mainlist);
		// 注册广播
		registerReceiver(
				mFocusNumBroadcastReceiver1, myIntentFilter);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(
				mFocusNumBroadcastReceiver1);
	}

	PullToZoomListView.HeadScrollInterface mHeadScrollInterface =  new PullToZoomListView.HeadScrollInterface() {
		
		@Override
		public void onHeadScroll(float value) {
			Log.d("outputdata","onHeadScroll value:" + value);
			//mTitleView.setAlpha(value);
		}
	};
	
	private void setforResult(){
		/*  	List<DiscoverDto> dtoList = mFundAdapter.getDataList();
		  	DiscoverDtos dtos = new DiscoverDtos();
		  	dtos.data = dtoList;
		  	Gson gson = new Gson();
		  	String dtosStr = gson.toJson(dtos);
			Intent tmpIntent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putSerializable("attentions", dtosStr);
			tmpIntent.putExtras(bundle);
			this.setResult(Activity.RESULT_OK,
					tmpIntent);*/
			}
	
	@Override
	public void onBackPressed() {
		setforResult();
		super.onBackPressed();
	}
	
}
